package com.bgs.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author: D.c_h
 * @create: 2021-07-08 22:20
 **/
@Component
public class TokenHelper {

    public final long EXPIRE = 1000 * 60 * 60 * 24;
    public final String APP_SECRET = "This is a randomly generated random secret key";
    public final String ID = "id";
    @Autowired
    private StringRedisTemplate redisTemplate;

    public String create(Integer id) {
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("D.c_h")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim(ID, id)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
        try {
            redisTemplate.opsForValue().set(id == null ? null : String.valueOf(id), JwtToken, 5, TimeUnit.HOURS);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Redis创建token失败！检查Redis服务============>");
            return "";
        }
        return JwtToken;
    }

    public boolean check(String str) {
        boolean result = false;
        if (!StringUtils.isEmpty(str)) {
            String id = null;
            try {
                Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(str);
                Claims claims = claimsJws.getBody();
                id = claims.get(ID).toString();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("token check error convert exception");
            }
            String authenticatedToken = redisTemplate.opsForValue().get(id);
            if (authenticatedToken != null && authenticatedToken.equals(str)) {
                result = true;
            }
        }
        return result;
    }

    public String convertToken(HttpServletRequest request) {
        String id = "";
        try {
            String token = request.getHeader(NormalConstant.AUTHORIZATION);
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            id = claims.get(ID).toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("token check error convert exception");
        }
        return id;
    }

    public String convertTokenByStr(String token) {
        String id = "";
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            id = claims.get(ID).toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("token check error convert exception");
        }
        return id;
    }

    public boolean delete(HttpServletRequest request) {
        String id = null;
        try {
            Jws<Claims> claimsJws = Jwts.parser().
                    setSigningKey(APP_SECRET).
                    parseClaimsJws(request.getHeader(NormalConstant.AUTHORIZATION));
            Claims claims = claimsJws.getBody();
            id = claims.get(ID).toString();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return redisTemplate.delete(id);
    }
}
